package com.limanyik.family.common.utils;

import com.limanyik.family.common.entity.BasisUser;
import com.limanyik.family.common.sinterface.entity.WebUserData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.Serializable;

@Component
public class UserUtil implements Serializable {

    private static UserUtil userUtil;

    /**
     * 存储用户token文件夹
     */
    public static String USER_FOLDER = "USER_FOLDER";

    /**
     * 存储用户token文件夹
     */
    public static String USER_TOKEN = "USER_TOKEN";

    @Resource(name = "redisTemplate")
    RedisTemplate redisTemplate;

    @PostConstruct
    private void init() {
        userUtil = this;
    }

    /**
     * 根据token缓存用户
     *
     * @param key
     * @return
     */
    public static boolean setCache(Object obj, String key) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        userUtil.redisTemplate.opsForValue().set(key, obj);
        return true;
    }

    /**
     * 根据token获取用户
     *
     * @param key
     * @return
     */
    public static Object getCache(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return userUtil.redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除缓存信息
     *
     * @param key
     * @return
     */
    public static boolean delCache(String key) {
        if (StringUtils.isBlank(key)) {
            return false;
        }
        userUtil.redisTemplate.delete(key);
        return true;
    }

    /**
     * 获取web用户信息
     *
     * @param token
     * @return
     */
    public static WebUserData getWebUserCacheByToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        if (null == userUtil) {
            userUtil = new UserUtil();
        }
        return (WebUserData) userUtil.redisTemplate.opsForValue().get(USER_TOKEN + ":" + token);
    }

    /**
     * 获取admin账户信息
     *
     * @param
     * @return
     */
    public static BasisUser getAdminUser() {
        BasisUser basisUser = new BasisUser();
        basisUser.setNickName("admin");
        basisUser.setId("001");
        return basisUser;
    }

}
